package tech.yunqian.slim.project.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SpecificFunctionService {
    @Value("${specificFunction.url}")
    private String specificFunctionUrl;

    @Autowired
    private AsyncHttpRequestService asyncHttpRequestService;

    private String getPayloadDigest(JSONObject data, JSONObject params, String token) {
        String digest = null;
        List<String> pieces = new ArrayList<>();
        List<String> dataKeys = new ArrayList<>(data.keySet());
        Collections.sort(dataKeys);
        for (String dataKey: dataKeys) {
            String value = data.get(dataKey).toString();
            pieces.add(String.format("%s=%s", dataKey, value));
        }
        List<String> paramKeys = new ArrayList<>(params.keySet());
        Collections.sort(paramKeys);
        for (String parameterKey: paramKeys) {
            String value = params.get(parameterKey).toString();
            pieces.add(String.format("%s=%s", parameterKey, value));
        }
        pieces.add(String.format("token=%s", token));
        String raw = String.join("&", pieces);
        digest = DigestUtils.sha1Hex(raw);
        return digest;
    }

    public JSONObject call(JSONObject request) {
        JSONObject result = null;
        String code = request.getString("code");
        JSONObject data = request.getJSONObject("data");
        JSONObject params = request.getJSONObject("params");
        String token = request.getString("token");
        String digest = getPayloadDigest(data, params, token);
        String url = String.format("%s%s", specificFunctionUrl, code);
        List<String> headers = new ArrayList<>();
        JSONObject payload = new JSONObject();
        payload.put("data", data);
        payload.put("params", params);
        payload.put("digest", digest);
        log.info("{} {}", url, payload);
        Future<String> future = asyncHttpRequestService.post(url, headers, payload);
        String response = null;
        try {
            response = future.get();
            result = JSONObject.parseObject(response);
            log.info("gun: {}", result);
        } catch (Exception e) {
            log.info(e.getMessage());
            StackTraceElement[] traces = e.getStackTrace();
            for (StackTraceElement trace : traces) {
                log.debug(trace.toString());
            }
        }
        return result;
    }
}
